package library.loaders
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.ImageLoader;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.SWFLoader;
	import com.greensock.loading.data.ImageLoaderVars;
	import com.greensock.loading.data.LoaderMaxVars;
	import com.greensock.loading.data.SWFLoaderVars;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.system.ApplicationDomain;
	
	/**
	 * 加载存放资源（图片、swf、元件等）
	 * @author vincent 2012年7月25日13:29:59
	 * 
	 */	
	public class UILoader extends LoaderMax
	{
		protected var mLibrarys:Vector.<SWFLoader>;
		
		protected var mApplicationDomain:ApplicationDomain;
		
		public function UILoader(vars:LoaderMaxVars = null, applicationDomain:ApplicationDomain=null)
		{
			super(vars);
			
			mApplicationDomain = applicationDomain || new ApplicationDomain();
			
			addEventListener(LoaderEvent.PROGRESS, onProgress);
		}
		
		protected function onProgress(event:LoaderEvent):void
		{
			print(event.text,event);
		}
		
		public function appendImage(url:String, vars:ImageLoaderVars = null):void
		{
			append(new ImageLoader(url, vars));
		}
		public function getImage(nameOrURL:String):Bitmap
		{
			return (this.getLoader(nameOrURL) as ImageLoader).rawContent;
		}		
		public function appendUILibrary(swfUrl:String, vars:SWFLoaderVars = null):void
		{
			const swfLoader:SWFLoader = new SWFLoader(swfUrl, vars);
			append(swfLoader);

			if(!mLibrarys)
				mLibrarys = new <SWFLoader>[swfLoader];
			else
				mLibrarys = mLibrarys.concat(new <SWFLoader>[swfLoader]);
		}
		
		public function getClass(className:String, swfNameOrUrl:String = null):Class
		{
			var swf:SWFLoader;
			var cls:Class;
			
			if(swfNameOrUrl)
			{
				swf = getLoader(swfNameOrUrl);
				if(swf)
				{
					cls = swf.getClass(className);
					if(cls)return cls;
				}
			}
			for each(swf in mLibrarys)
			{
				try
				{
					cls = swf.getClass(className);
				} 
				catch(e:Error) 
				{
					
				}
				if(cls)return cls;
			}
			return null;
		}
		public function getUI(className:String, swfNameOrUrl:String = null):DisplayObject
		{
			var cls:Class = getClass(className, swfNameOrUrl);
			var ui:DisplayObject;
			if(cls)
				ui = new cls();
			return ui;
		}
	}
}